package com.atguigu.chapter07.a_window;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * @ClassName: Flink01_Tumbling_Window
 * @Description:
 * @Author: kele
 * @Date: 2021/4/6 20:06
 *
 * 时间窗口
 *      包括：滚动事件
 *          滑动事件
 **/
public class Flink04_Count_Event_Window {

    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port",20000);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        DataStreamSource<String> ds = env.socketTextStream("hadoop162", 8888);

        ds.flatMap(new FlatMapFunction<String, Tuple2<String,Long>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Long>> out) throws Exception {

                for (String word : line.split(" ")) {
                    out.collect(Tuple2.of(word,1l));
                }
            }
        })
                .keyBy(d -> d.f0)
              //.countWindow(5,2)
                .countWindow(5,3)
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, GlobalWindow>() {

                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<Tuple2<String, Long>> elements,
                                        Collector<String> out) throws Exception {

                        ArrayList<Tuple2<String, Long>> list = new ArrayList<>();

                        for (Tuple2<String, Long> element : elements) {
                            list.add(element);
                        }

                        out.collect("元素个数："+list.size());

                    }
                }).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
